package kpi.javatraining6.gnatiuk.src.tester.user;

import java.lang.reflect.Field;
import java.nio.file.NoSuchFileException;

import kpi.javatraining6.gnatiuk.src.teachingsystem.TopicCombiner;
import kpi.javatraining6.gnatiuk.src.tester.Logger;
import kpi.javatraining6.gnatiuk.src.tester.QuestionnaireController;
import kpi.javatraining6.gnatiuk.src.tester.inout.Input;

public class UserController {

	protected enum UserCommands {HELP, STAT, START, CLOSE, SHOW_STATS}

	
	private User user;
	private QuestionnaireController questionnaireController;


	public UserController(User user) {
		this.user = user;
    }

	public void run() throws NoSuchFileException {
		UserCommands command;
		do{
            System.out.println(String.format("Enter a command e.g. \"%s\"", UserCommands.HELP));
			command = UserCommands.valueOf(Input.getInstance().get().toUpperCase());
			processCommand(command);
		}while(!command.equals(UserCommands.CLOSE));
	}

    protected void processCommand(UserCommands command) throws NoSuchFileException {
        switch (command) {
            case STAT:
                showStatistic();
                break;
            case START:
                start();
                break;
            case HELP:
                help();
                break;
            default:
                break;
        }
    }


    private void showStatistic(){
        System.out.println(user.getStatistic());
    }

	private void loadQuestionnaire() throws NoSuchFileException {
            questionnaireController = new QuestionnaireController(user , new TopicCombiner().getQuestionnaires());
            System.out.println("The source was loaded");
	}

    private void start() throws NoSuchFileException {
        loadQuestionnaire();
        if(questionnaireController !=null){
            Logger.getInstance().recordUserAction(user.getUserName(), "started");
            questionnaireController.run();
        }else{
            System.err.println("Questionnaire wasn't chosen");
        }
    }

	protected void help(){
        System.out.println(getCommands());
	}

	private String getCommands(){
		String commands="";
		Class<UserController> thisObject = UserController.class;
		Field[] publicFields = thisObject.getDeclaredFields();
		int number=1;
		for (Field field : publicFields) {
			if(field.getType().getName().equals(String.class.getName())){
				try {
					commands+=String.format("%d. %s\n",number++, field.get(field.getName()).toString());
				} catch (IllegalArgumentException | IllegalAccessException e) {
					e.printStackTrace();
				}
            }
		}
		return commands;
	}
}
